package com.gege.inbound;

import com.gege.outbound.HttpOutboundHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 服务端http入站处理器
 *
 * @author gechenpeng
 * @date 2021-03-31
 */
@Sharable
@Slf4j
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {

    private HttpOutboundHandler handler;

    public HttpInboundHandler(List<String> endpoints) {
        this.handler = new HttpOutboundHandler(endpoints);
    }

    /**
     * 当从Channel读取数据时被调用
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
            this.handler.handle(fullHttpRequest, ctx);
        } finally {
            // 丢弃已接收的消息
            // 当某个 ChannelInboundHandler 的实现重写 channelRead()方法时,
            // 它将负责显式地释放与池化的 ByteBuf 实例相关的内存。
            // Netty 为此提供了一个实用方法 ReferenceCountUtil.release()
            ReferenceCountUtil.release(msg);
        }
    }

    /**
     * 当处理过程中在ChannelPipeline中有错误产生时被调用
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("http inbound handler exception", cause);
        ctx.close();
    }
}
